﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;

namespace NbfsiLogin
{
    public partial class Form1 : Form
    {
        private String SessionID;
        public Form1()
        {
            InitializeComponent();
            SessionID = GetSessionID();
            GetVerifyCode();

            RegistryKey regRead;
            regRead = Registry.CurrentUser.OpenSubKey("Software\\NbLogin", true);
            if (regRead == null) //如果该子键不存在
            {
                //写注册表
                RegistryKey regWrite;
                regWrite = Registry.CurrentUser.CreateSubKey("Software\\NbLogin");
                regWrite.SetValue("browser", @"C:\Program Files\Internet Explorer\IEXPLORE.EXE");
                //关闭该对象
                regWrite.Close();
            }
            else
            {
                object obj = regRead.GetValue("browser"); //读取“Name”项的值
                textBox2.Text = obj.ToString(); //显示在TextBox里

                if (String.IsNullOrEmpty(obj.ToString()))
                {
                    textBox2.Text = @"C:\Program Files\Internet Explorer\IEXPLORE.EXE";
                }
            }
            //关闭该对象
            regRead.Close();
        }

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);


        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetGetCookie(string url, string name, StringBuilder data, ref int dataSize);  


        private string GetSessionID()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.nbfsi.gov.cn/spjcgx/login.jsp");
            request.Method = "GET";
            request.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*";
            request.Headers.Add("Accept-Language", "zh-CN;");
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            request.Headers.Add("Accept-Encoding", "gzip, deflate;");
            request.Host = "www.nbfsi.gov.cn";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();


            String cookie = response.Headers.Get("Set-Cookie");
            String[] keyVal = cookie.Split(';');

            for (int i = 0; i < keyVal.Length; i++)
            {
                string temp = keyVal[i];
                if (temp.LastIndexOf("JSESSIONID") > -1)
                {
                    return temp.Split('=')[1];
                }
            }
            return "";
        }

        private void GetQueryData()
        {
            String postDataStr = "action=getLoginName&uuid=ac868bbe-a44a-4185-bb54-67d741c2867c";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.nbfsi.gov.cn/spjcgx/initialUsbkey/queryData.jsp");
            request.Method = "POST";
            request.Headers.Add("x-requested-with","XMLHttpRequest");
            request.Accept = "application/json, text/javascript, */*";
            request.Referer = "http://www.nbfsi.gov.cn/spjcgx/login.jsp";
            request.Headers.Add("Accept-Language", "zh-CN;");
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            request.Headers.Add("Accept-Encoding", "gzip, deflate;");
            request.Host = "www.nbfsi.gov.cn";
            //request.Connection = "Keep-Alive";
            request.Headers.Add("Pragma", "no-cache;");
            request.Headers.Add("Cookie", String.Format("JSESSIONID={0}", SessionID));

            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
        }

        private void GetVerifyCode()
        {

            CookieContainer cookieContainer = new CookieContainer();
            Cookie cookiesave = new Cookie();
            cookiesave.Domain = "www.nbfsi.gov.cn";
            cookiesave.Name = "save";
            cookiesave.Value = "false";
            cookiesave.Path = @"/spjcgx/applications/terminal/";
            cookiesave.Expires = DateTime.Parse("3000/2/1 0:00:00");
            cookieContainer.Add(cookiesave);

            Cookie JSessionId = new Cookie();
            JSessionId.Domain = "nbfsi.gov.cn";
            JSessionId.Name = "JSESSIONID";
            JSessionId.Value = SessionID;
            JSessionId.Path = @"/";
            JSessionId.Expires = DateTime.Parse("3000/2/1 0:00:00");
            cookieContainer.Add(JSessionId);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.nbfsi.gov.cn/spjcgx/verifycode.jsp");
            request.Method = "GET";
            request.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*";
            request.Headers.Add("Accept-Language", "zh-CN;");
            request.Referer = "http://www.nbfsi.gov.cn/spjcgx/login.jsp";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            request.Headers.Add("Accept-Encoding", "gzip, deflate;");
            request.Host = "www.nbfsi.gov.cn";
            request.Headers.Add("Cookie", String.Format("JSESSIONID={0}", SessionID));
            request.CookieContainer = cookieContainer;


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            pictureBox1.Image = Image.FromStream(myResponseStream);
            myResponseStream.Close();


           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetQueryData();
            string JSessionID = SessionID;
            String verifyCode = textBox1.Text;
            String postDataStr = String.Format("uuid=ac868bbe-a44a-4185-bb54-67d741c2867c&ukey=83a432e3-c19b-41b4-8477-4c56f671c093&md5=bd6a317a2c9568b3496ebca5433c87ad&loginName=Yujp1&password=123456&verifycode={0}", verifyCode);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.nbfsi.gov.cn/spjcgx/login.jsp");
            request.Method = "POST";
            request.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, */*";
            request.Referer = "http://www.nbfsi.gov.cn/spjcgx/login.jsp";
            request.Headers.Add("Accept-Language", "zh-CN;");
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            request.Headers.Add("Accept-Encoding", "gzip, deflate;");
            request.Host = "www.nbfsi.gov.cn";
            //request.Connection = "Keep-Alive";
            request.Headers.Add("Pragma","no-cache;");
            request.Headers.Add("Cookie", String.Format("save=null; JSESSIONID={0}", JSessionID));

            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            //CookieCollection myCookies = new CookieCollection();
            //myCookies.Add(response.Cookies); //添加cookie
            //foreach (Cookie cookie in myCookies) //将cookie设置为浏览的cookie
            //{
            //    InternetSetCookie(
            //         "http://" + cookie.Domain.ToString(),
            //         cookie.Name.ToString(),
            //         cookie.Value.ToString() + ";expires=Sun,22-Feb-2099 00:00:00 GMT");
            //}

            bool b = InternetSetCookie("http://www.nbfsi.gov.cn/spjcgx/login.jsp", "JSESSIONID", JSessionID + ";Path=/;expires=Sun,22-Feb-2099 00:00:00 GMT");
            b = InternetSetCookie("http://www.nbfsi.gov.cn/spjcgx/login.jsp", "save", "null;Path=/;expires=Sun,22-Feb-2099 00:00:00 GMT");
            System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\IEXPLORE.EXE", "http://www.nbfsi.gov.cn/spjcgx/applications/terminal/Desktop.jsp");
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            GetVerifyCode();
        }
      
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            //写注册表
            RegistryKey regWrite;
            regWrite = Registry.CurrentUser.CreateSubKey("Software\\NbLogin");
            regWrite.SetValue("browser", textBox2.Text);
            //关闭该对象
            regWrite.Close();
        }

     
    }
}
